package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import one.stand.code.RedisCode;
import one.stand.enums.LoginEnum;
import one.stand.model.*;
import one.stand.request.BusinessCardRequest;
import one.stand.request.CustomerRequest;
import one.stand.request.UserTaskRequest;
import one.stand.service.BaseService;
import one.stand.service.UserTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author Administrator
 */
@Service
public class UserTaskServiceImpl extends BaseService implements UserTaskService {

    @Override
    public ResultModel addMoneyNum(UserTaskRequest request) {
        log.info("设定员工月目标：{}", JSON.toJSONString(request));
        if (request == null || request.getCardId() == null) {
            return ResultModel.checkParamFail();
        }
        if (request.getRoleId() <= 0 && !request.getMyCardId().equals(request.getCardId())) {
            return ResultModel.fail("你不是老板，无法设定成员目标");
        }
        if(request.getCustomerNum() == null){
            request.setCustomerNum(0);
        }
        if(request.getTargetAmount() == null){
            request.setTargetAmount(0);
        }
        UserTaskModel model1 = userTaskMapper.select(new UserTaskModel() {{
            setCardId(request.getCardId());
            setCreateTime(new Date());
        }});
        UserTaskModel model = new UserTaskModel();
        BeanUtils.copyProperties(request, model);
        // 查询本月已录入的成交金额
        Integer completeCustomerNum = inputDealMoneyMapper.selectDelMoney(request.getCardId());
        // 查询本月已录入的客户数
        Integer completeTargetAmount = customerMapper.selectCustomerNum(request.getCardId());
        // 完成状态1未完成  2已完成
        if (completeCustomerNum >= request.getCustomerNum() && completeTargetAmount >= request.getTargetAmount()) {
            model.setCompletionStatus(2);
        } else {
            model.setCompletionStatus(1);
        }
        // 完成金额数
        model.setCompleteCustomerNum(completeCustomerNum);
        // 完成客户数
        model.setCompleteTargetAmount(completeTargetAmount);
        if (model1 != null) {
            model.setTaskId(model1.getTaskId());
            r = userTaskMapper.updateByPrimaryKeySelective(model);
            if (r > 0) {
                return ResultModel.success();
            }
        } else {
            model.setCompanyId(request.getCId().intValue());
            model.setCreateUserId(request.getId().intValue());
            model.setIsDel(0);
            model.setCreateTime(new Date());
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            // 得到当前月最后一天
            model.setEndTime(calendar.getTime());
            model.setCardId(request.getCardId());
            r = userTaskMapper.insertSelective(model);
            if (r > 0) {
                return ResultModel.success();
            }
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel moveCustomer(CustomerRequest request) {
        log.info("移交客户：{}", JSON.toJSONString(request));
        if (request == null || request.getCustomerIds() == null || request.getCustomerState() == null) {
            return ResultModel.checkParamFail();
        }
        if(request.getRoleId() != null && request.getRoleId() <= 0) {
            List<CustomerModel> list = customerMapper.selectCustomerAllInfo(new CustomerModel() {{
                setIds(request.getCustomerIds().split(","));
            }});
            for (CustomerModel model : list) {
                boolean fal = !request.getMyCardId().equals(model.getAscriptionId().intValue());
                if (fal) {
                    return ResultModel.fail("员工只能移交自己的独占客户~！");
                }
            }
        }
        boolean fal = request.getAscriptionId() != null && request.getMyCardId() == request.getAscriptionId().intValue() && request.getCustomerState() == 1;
        if(fal){
            return ResultModel.fail("客户不能移交给自己~！");
        }
        CustomerModel model = new CustomerModel();
        model.setIds(request.getCustomerIds().split(","));
        model.setCustomerState(request.getCustomerState());
        if (request.getCustomerState() == 1) {
            model.setAscriptionId(request.getAscriptionId());
        }
        customerMapper.updateMoveCustomer(model);
        return ResultModel.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel quitCompany(BusinessCardRequest request) {
        log.info("员工退出企业：{}", JSON.toJSONString(request));
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if(request.getRoleId() > 0 && request.getCardId().equals(request.getMyCardId())){
            return ResultModel.fail("BOSS不能移除自己哦~!");
        }
        if(request.getRoleId() <= 0 && !request.getCardId().equals(request.getMyCardId())){
            return ResultModel.fail("权限不足~!");
        }
        // 查询公司购买服务数
        CompanyServiceModel companyServiceModel = companyServiceMapper.selectCompanyService(new CompanyServiceModel() {{
            setCompanyId(request.getCId().intValue());
            setType(1);
        }});
        if (companyServiceModel == null) {
            return ResultModel.fail("操作失败，未找到公司购买服务记录信息~!");
        }
        CustomerModel model = new CustomerModel();
        model.setAscriptionId(request.getCardId().longValue());
        model.setIsDel(0);
        model.setCustomerState(1);
        List<CustomerModel> list = customerMapper.getCustomer(model);
        if (list != null && list.size() > 0) {
            return ResultModel.fail("该员工下有独立客户，无法移除~!");
        }
        r = businessCardMapper.delBusinessCard(new BusinessCardModel() {{
            setIsDel(1);
            setCardId(request.getCardId());
        }});
        if (r > 0) {
            // 公司购买名片服务记录表
            Integer serviceId = companyServiceModel.getServiceId();
            companyServiceModel.setHistoryNum(companyServiceModel.getAvailableNum());
            companyServiceModel.setAvailableNum(companyServiceModel.getAvailableNum() + 1);
            companyServiceModel.setCreateTime(currentDate());
            companyServiceModel.setPurchaseType(3);
            companyServiceModel.setServiceId(null);
            r = companyServiceMapper.insertSelective(companyServiceModel);
            if (r > 0) {
                // 修改之前的名片服务记录表为记录
                companyServiceMapper.updateByPrimaryKeySelective(new CompanyServiceModel() {{
                    setType(0);
                    setServiceId(serviceId);
                }});
            }
            // 删除用户月目标数据
            userTaskMapper.delUserTask(new UserTaskModel() {{
                setCardId(request.getCardId());
            }});
            // 删除缓存
            batchDelToken(new ArrayList<BusinessCardModel>(){{
                add(new BusinessCardModel(){{
                    setUserId(request.getUserId().intValue());
                }});
            }});
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel dissolutionCompany(BusinessCardRequest request) {
        log.info("解散企业：{}", JSON.toJSONString(request));
           if (request == null || request.getCId() == null) {
               return ResultModel.checkParamFail();
           }
           // 查询公司名片信息
           List<BusinessCardModel> businessCardModelList = businessCardMapper.selectList(new BusinessCardModel() {{
               setCompanyId(request.getCId().intValue());
               setIsDel(0);
               setState(1);
           }});
           // 删除名片表
           BusinessCardModel model = new BusinessCardModel();
           model.setCompanyId(request.getCId().intValue());
           model.setIsDel(1);
           businessCardMapper.delBusinessCard(model);
           // 删除公司
           CompanyModel companyModel = new CompanyModel();
           companyModel.setCompanyId(request.getCId().intValue());
           companyModel.setIsDel(BaseModel.YES_DEL);
           companyMapper.updateByPrimaryKeySelective(companyModel);

           // 修改用户role信息
           userMapper.updateByPrimaryKeySelective(new UserModel() {{
               setRoleId(0);
               setUserId(request.getId());
           }});
           // 删除用户月目标数据
           userTaskMapper.delUserTask(new UserTaskModel() {{
               setCompanyId(request.getCId().intValue());
           }});
           // 删除缓存
           batchDelToken(businessCardModelList);

           // 解散公司*删除用户收藏的产品和文章
            delCollectionFun(request.getCId().intValue());
           return ResultModel.success();
    }
    @Override
    public ResultModel<Boolean> batchDelToken(Integer companyId) {
        // 查询公司名片信息
        List<BusinessCardModel> businessCardModelList = businessCardMapper.selectList(new BusinessCardModel() {{
            setCompanyId(companyId);
            setIsDel(0);
            setState(1);
        }});

        return batchDelToken(businessCardModelList);
    }

    public ResultModel<Boolean> batchDelToken(List<BusinessCardModel> businessCardModelList) {
        //TODO 解散企业退出企业只删除该名片的信息
        Set<String> keyList=new HashSet<>();
        for (BusinessCardModel model : businessCardModelList) {
            if(model.getUserId() != null) {
                keyList.addAll(redisUtil.getKey(RedisCode.getImList(model.getUserId().longValue(), LoginEnum.CRM.getCode())));
                keyList.addAll(redisUtil.getKey(RedisCode.getUserWebSocketMessageRecord(model.getUserId()+"","*",LoginEnum.CRM.getCode())));
                keyList.addAll(redisUtil.getKey(RedisCode.getUnreadMessage(model.getUserId()+"","*",LoginEnum.CRM.getCode())));
                keyList.addAll(redisUtil.getKey(RedisCode.getUserLoginToken("*"+model.getUserId())));
                keyList.addAll(redisUtil.getKey(RedisCode.getUnreadNum(model.getUserId().toString(),"*",LoginEnum.CRM.getCode())));
            }
        }
        log.info("公司解散需要删除得key:{}", JSON.toJSONString(keyList));
        redisUtil.batchDel(keyList);
        return ResultModel.success(true);
    }

    /**
     * 解散公司*删除用户收藏的产品和文章
     *
     * @param companyId
     */
    @Override
    @Async("asyncServiceExecutor")
    public void delCollectionFun(Integer companyId){
        if(companyId == null){
            return;
        }
        // 调用存储过程
        collectionMapper.delCollectionFun(companyId);
    }
}
